import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/util/http'
import VuexPersistence from 'vuex-persist'
import Cookies from 'js-cookie'

// 这个cookie似乎出问题了
// const vuexCookie = new VuexPersistence({
//   // ...your options
//   restoreState: (key, storage) => Cookies.get(key),
//   saveState: (key, state, storage) =>
//     Cookies.set(key, state, {
//       expires: 3
//     }),
//     reducer: (state) => {
//       return {
//         cityId: state.cityId,
//         cityName: state.cityName
//       }
//     }

// })

const vuexLocal = new VuexPersistence({
  key: 'city',
  // ...your options
  reducer: (state) => {
    return {
      cityId: state.cityId,
      cityName: state.cityName
    }
  }
})

Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [vuexLocal.plugin],
  state: {
    cityId: '440300',
    cityName: '深圳',
    cinemas: [],
    isNavShow: true,
    navBarHeight: 100
  },
  getters: {
  },

  // 注意mutations只能支持同步操作
  // 专门面向state工作，为更新state而生，能被devtools监测
  mutations: {
    changeCity (state, city) {
      state.cityName = city.name
      state.cityId = city.cityId
      // 这里给cinemas赋值空是为了当城市改变时，再次请求，再Cinemas.vue里有请求前有判断：state.cinemas = []？为空才会请求
      state.cinemas = []
      // console.log(state)
    },

    changeCinemas (state, cinemas) {
      state.cinemas = cinemas
    },
    hideNav (state) {
      state.isNavShow = false
    },
    showNav (state) {
      state.isNavShow = true
    },
    getNavBarHeight (state, height) {
      console.log(height)
      state.navBarHeight = height
    }
  },

  // 支持异步和同步
  // 异步请求得到数据后仍然要走mutation更改数据，才能被devtools监测
  // actions内部的方法第一个参数就是store和this.$store一样
  actions: {
    getCinemas (store) {
      return http({
        url: `/gateway?cityId=${store.state.cityId}&ticketFlag=1&k=6463571`,
        headers: {
          'X-Host': 'mall.film-ticket.cinema.list'
        }
      }).then((res) => {
        console.log(res)
        // store.state.cinemas = res.data.data.cinemas;  //不要直接改状态, 通过mutation更规范,可以被监测
        store.commit('changeCinemas', res.data.data.cinemas)

        // console.log(this.cinemas);
        // console.log(document.getElementsByTagName("li").length);
      })
    }
  },
  modules: {
  }
})
